# -*- coding: UTF-8 -*-

# Create your views here.
from django.shortcuts import render, get_object_or_404

# from django.contrib.auth.decorators import login_required
from django.forms.models import model_to_dict
from django.http import JsonResponse,HttpResponse
import pymysql
from saltstack.salt_api import SaltAPI
from userlog.function import SaveUserlog

class Public(object):
    def __init__(self,*args,**kwargs):
        super(Public, self).__init__()
        self._abcd='test'
        self.mysql_connect = pymysql.connect(host="122.226.199.218", user="salt", port=3309,
                                             passwd="saltUqeG0xPvz8Iqum7", charset="utf8", db="salt")
        self.cursor = self.mysql_connect.cursor()
        self.Saltapi = SaltAPI()


    def post(self,*args,**kwargs):
        func = self.request.GET.get('option','undefined')
        if func =='del':
            func="delete"
        return getattr(self, func)()
        # try:
        #     return getattr(self, func)()  #类反射机制 自动调用html传来的对应的参数名称
        # except Exception as e:
        #     print(e)
        #     return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})


    def get(self,*args,**kwargs):  #分页相关
        form = self.form
        search_form = self.searchform(auto_id=False)
        ONE_PAGE_OF_DTAA = 0
        try:
            curpage = int(self.request.GET.get('curpage', '1'))
            allpage = int(self.request.GET.get('allpage', '1'))
            try:
                ONE_PAGE_OF_DTAA = int(self.request.COOKIES["pageper"])
            except Exception:
                pass
        except ValueError as  e:
            print(e)
            curpage = 1
            allpage = 1
            pagetype = ''
            ONE_PAGE_OF_DTAA = 15

        if ONE_PAGE_OF_DTAA == 0:
            ONE_PAGE_OF_DTAA = 10
        startops = (curpage - 1) * ONE_PAGE_OF_DTAA
        endpos = startops + ONE_PAGE_OF_DTAA
        posts = self.models.objects.all()[startops:endpos]

        # print startops, endpos
        if curpage == 1 and allpage == 1:
            allpostcounts = self.models.objects.count()
            allpage = allpostcounts // ONE_PAGE_OF_DTAA
            remainpost = allpostcounts % ONE_PAGE_OF_DTAA
            if remainpost > 0:
                allpage += 1
        pagelist = range(1, int(allpage) + 1)
        url_name =self.url_name 
        return render(self.request, self.template_name, locals())

    def search(self,*args,**kwargs):
        form=self.form
        search_form=self.searchform(auto_id=False)
        queryset=self.models.objects.all()
        search_form = self.searchform(self.request.POST or None)
        if search_form.is_valid():
            cleaned_data = search_form.cleaned_data
            for key in cleaned_data:
                if cleaned_data[key]:
                    queryset = queryset.filter(**{key: cleaned_data[key]})
        posts=queryset
        url_name =self.url_name
        return render(self.request, self.template_name, locals())


    def add(self,*args,**kwargs):
        form = self.form(self.request.POST or None)

        # 判断form是否有效
        if form.is_valid():
            try:
                form.save()
                return JsonResponse({'msg': "post form data save successful"}, safe=False)
            except Exception as e:
                print(e)
                return JsonResponse({'msg': str(e)}, safe=False)
        else:
            return JsonResponse({'msg': "post form data  vailadate failed %s" %str(form.errors)}, safe=False)


    def update(self,*args,**kwargs):
        print('update')
        id = self.request.POST.get('id')
        server = get_object_or_404(self.models, pk=int(id))
        form = self.form(self.request.POST, instance=server)

        if form.is_valid():
            server = form.save()

            server.save()
            return JsonResponse({'msg': "update form data successful"}, safe=False)
        else:
            print('abcddef')
            print(str(form.errors))
            return JsonResponse({'msg': str(form.errors)}, safe=False)

    def delete(self, *args, **kwargs):
        server_id = self.request.POST.get("serverid")
        server_id = server_id.split('.')
        t = [int(x.strip()) for x in server_id]
        try:
            rows = self.models.objects.filter(id__in=t)
            rows.delete()
        except Exception as e:
            print(e)
            return JsonResponse({'msg': "删除失败"}, safe=False)
        return JsonResponse({'msg': "删除成功"}, safe=False)

    def query(self,*args,**kwargs):
        server_id = self.request.POST.get('serverid',0)
        rows = model_to_dict(get_object_or_404(self.models,pk=int(server_id)))
        return JsonResponse(rows, safe=False)


    def url_get(self,request,app,template,form,models,search_form,querykey="",*args,**kwargs):
        self.request = request
        self.models = models
        self.searchform = search_form
        self.querykey = querykey
        self.app = app
        self.form = form
        self.template = template
        self.template_name = '%s/%s.html' % (self.app, self.template)
        self.url_name = self.template
        self.queryset=kwargs.get('queryset',None)
        cls = SaveUserlog()
        cls(request)
        if self.request.method =="GET":
            return self.get()
        elif self.request.method == "POST":
            return self.post()
        else:
            return  HttpResponse("unkown http requset method")


import logging
class Public_loggining(object):
    def __init__(self,*args,**kwargs):
        super(Public_loggining, self).__init__()


        logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='django_app.log',
                        filemode='w')

    #################################################################################################
    # 定义一个StreamHandler，将INFO级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象#
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
        console.setFormatter(formatter)
        logging.getLogger('').addHandler(console)
        self.log=logging

# class Public_SSH(object):
#     def __init__(self,*args,**kwargs):
#         super(Public_SSH, self).__init__()
#         self.cur_dir= os.path.dirname(os.path.abspath('__file__'))
#         self.key_filename=os.path.join(self.cur_dir,"cmdb/Identity.pub")
#     def get_ssh_client(self):
#         SSH_Client=ServerParamikoMixin(ip=hostip,port=port,username=user,key_filename=key_filename)
#         return SSH_Client



# class Public_Menu(object):
#     def __init__(self,*args,**kwargs):
#         super(Public_Menu, self).__init__()
#
#     def get_url_args(self,request):
#         user = request.user
#         userid = User.objects.get(username=user).id
#         rows = Menu.objects.filter(parent_id=0)
#         user_url_list=MyUserMenu.objects.get(user_id=userid).menus_show
#         user_url_list= user_url_list.split(",")
#         urlrows= Menu.objects.filter(id__in=user_url_list)
#         allurlrows=Menu.objects.all()
#         return rows,urlrows,allurlrows
